'''
Revisionist: a module to get the latest source code revision for a Django project, 
for use as a static content versioning device. Currently supports Mercurial,
Subversion and Bazaar.

http://www.fairviewcomputing.com/blog/2008/03/03/automatic-django-static-content-versioning/

Copyright (c) 2008 Fairview Computing LLC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

'''
import logging
import os
import sys
import time

# Day of the year as a decimal number [001,366].
DEFAULT_REVISION = time.strftime("%j", time.localtime())

logger = logging.getLogger('revisionist')
if not logger.handlers:
    logger.addHandler(logging.StreamHandler(sys.stderr))

def _get_django_module_dir():
    django_module_dir = '.'
    if os.environ.has_key('DJANGO_SETTINGS_MODULE'):
        django_settings_module = __import__(os.environ['DJANGO_SETTINGS_MODULE'])
        return os.path.dirname(django_settings_module.__file__)
    else:
        logger.warn('DJANGO_SETTINGS_MODULE not set; using current directory.')
    return django_module_dir

def _findhgrepo(path = None):
    if not path:
        path = os.getcwd()
    while not os.path.isdir(os.path.join(path, '.hg')):
        oldpath, path = path, os.path.dirname(path)
        if path == oldpath:
            return ''
    return path

def bzrrev(path=None):
    '''
    Get the latest revision of the Django project from its Bazaar repository.
    '''
    revision = DEFAULT_REVISION
    try:
        from bzrlib import workingtree
        
        if not path:
            path = _get_django_module_dir()
        wt = workingtree.WorkingTree.open(path)
        revision = str(wt.branch.revno())
    except Exception, e:
        logger.warn('Could not determine Bazaar revision for %s: %s' % (path, e))
        logger.warn('Using default revision: %s' % DEFAULT_REVISION)
    return revision

def hgrev(path=None):
    '''
    Get the latest revision of the Django project from its Mercurial repository.
    '''
    revision = DEFAULT_REVISION
    try:
        from mercurial.hg import repository
        from mercurial.ui import ui
        
        if not path:
            path = _get_django_module_dir()
        repo = _findhgrepo(path)
        revision = str(repository(ui(interactive=False), repo).changelog.count())
    except Exception, e:
        logger.warn('Could not determine Mercurial revision for %s: %s' % (path, e))
        logger.warn('Using default revision: %s' % DEFAULT_REVISION)
    return revision

def svnrev(path=None):
    '''
    Get the latest revision of the Django project from its Subversion repository.
    Requires pysvn, available from http://pysvn.tigris.org/.
    '''
    revision = DEFAULT_REVISION
    try:
        import pysvn
        client = pysvn.Client()
        if not path:
            path = _get_django_module_dir()
        info = client.info(path)
        revision = str(info.revision.number)
    except Exception, e:
        logger.warn('Could not determine Subversion revision for %s: %s' % (path, e))
        logger.warn('Using default revision: %s' % DEFAULT_REVISION)
    return revision
